class UsersController < ApplicationController
  layout false
  skip_before_action :verify_authenticity_token

  def toggle_playlist
    if params[:klass] == "Playlist"
      playlists = current_user.playlists
      if playlists.exists?(params[:id])
        playlists.delete(Playlist.find(params[:id]))
        render plain: 'is_removed'
      else
        playlists << Playlist.find(params[:id])
        render plain: 'is_added'
      end
    else
      singers = current_user.singers
      if singers.exists?(params[:id])
        singers.delete(Singer.find(params[:id]))
        render plain: 'is_removed'
      else
        singers << Singer.find(params[:id])
        render plain: 'is_added'
      end
    end
  end

  def toggle_pick
    render plain: current_user.picklist.toggle_song(params[:id])
  end

  def toggle_fav
    render plain: current_user.song_fav.toggle_song(params[:id])
  end

  def add_history
    # 播放历史只增不减, 没有toggle这一说
    current_user.history.add_song(params[:id])
    head :ok
  end

  def song_view_count_increment
    Song.find(params[:id]).increment!(:view_amount)
    respond_to do |format|
      format.json { head :ok }
    end
  end

  private

    def songs_toggle_item(songs)
      if params[:force].present?
        songs << Song.find(params[:id]) rescue logger.info('唯一性索引生效, 已添加')
        render plain: 'is_added'
      else
        if songs.exists?(params[:id])
          songs.delete(Song.find(params[:id]))
          render plain: 'is_removed'
        else
          songs << Song.find(params[:id])
          render plain: 'is_added'
        end
      end
    end
end
